<template>
  <div class="page-config-editor">
    <el-card>
      <div slot="header" class="card-header">
        <span>页面配置</span>
        <div class="header-buttons">
          <el-button
            size="small"
            type="info"
            icon="el-icon-view"
            @click="showMergedConfig = !showMergedConfig"
          >
            {{ showMergedConfig ? '隐藏' : '查看' }}完整配置
          </el-button>
          <el-button
            size="small"
            type="warning"
            icon="el-icon-delete"
            @click="handleClear"
          >
            清除自定义
          </el-button>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-check"
            :loading="saving"
            @click="handleSave"
          >
            保存
          </el-button>
        </div>
      </div>

      <el-alert
        title="页面配置会覆盖网站全局配置"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 15px;"
      >
        只需设置需要覆盖的配置项，未设置的项将使用网站全局配置
      </el-alert>

      <el-form :model="pageConfig" label-width="120px">
        <el-form-item label="页面标题">
          <el-input
            v-model="pageConfig.title"
            placeholder="留空使用全局配置"
          />
        </el-form-item>

        <el-form-item label="页面描述">
          <el-input
            v-model="pageConfig.description"
            type="textarea"
            :rows="3"
            placeholder="留空使用全局配置"
          />
        </el-form-item>

        <el-form-item label="页面关键词">
          <el-input
            v-model="pageConfig.keywords"
            placeholder="留空使用全局配置"
          />
        </el-form-item>

        <el-form-item label="OG Image">
          <el-input
            v-model="pageConfig.og_image"
            placeholder="留空使用全局配置"
          />
        </el-form-item>

        <el-form-item label="自定义 CSS">
          <el-input
            v-model="pageConfig.custom_css"
            type="textarea"
            :rows="5"
            placeholder="输入自定义 CSS 代码"
          />
        </el-form-item>

        <el-form-item label="自定义 JS">
          <el-input
            v-model="pageConfig.custom_js"
            type="textarea"
            :rows="5"
            placeholder="输入自定义 JavaScript 代码"
          />
        </el-form-item>

        <el-form-item label="JSON 配置">
          <el-input
            v-model="jsonConfig"
            type="textarea"
            :rows="10"
            placeholder="高级用户可直接编辑 JSON"
            @blur="handleJsonChange"
          />
          <div style="margin-top: 5px;">
            <el-button size="mini" @click="formatJson">格式化</el-button>
            <el-button size="mini" @click="validateJson">验证</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 完整配置预览 -->
    <el-dialog
      title="完整配置（页面配置 + 全局配置）"
      :visible.sync="showMergedConfig"
      width="800px"
      append-to-body
    >
      <pre class="config-preview">{{ JSON.stringify(mergedConfig, null, 2) }}</pre>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPageConfig,
  updatePageConfig,
  clearPageConfig
} from '@/api/static_web/config'

export default {
  name: 'PageConfigEditor',
  props: {
    pageId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      pageConfig: {},
      mergedConfig: {},
      globalConfig: {},
      jsonConfig: '',
      saving: false,
      showMergedConfig: false
    }
  },
  watch: {
    pageId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.loadConfig()
        }
      }
    }
  },
  methods: {
    // 加载配置
    loadConfig() {
      getPageConfig(this.pageId).then(response => {
        const data = response.data
        this.pageConfig = data.page_config || {}
        this.mergedConfig = data.merged_config || {}
        this.globalConfig = data.global_config || {}
        this.jsonConfig = JSON.stringify(this.pageConfig, null, 2)
      })
    },
    // 保存配置
    handleSave() {
      this.saving = true

      updatePageConfig(this.pageId, this.pageConfig, true).then(response => {
        this.$message.success('页面配置保存成功')
        this.pageConfig = response.data.page_config
        this.mergedConfig = response.data.merged_config
        this.jsonConfig = JSON.stringify(this.pageConfig, null, 2)
        this.saving = false
        this.$emit('saved', response.data)
      }).catch(() => {
        this.$message.error('保存失败')
        this.saving = false
      })
    },
    // 清除自定义配置
    handleClear() {
      this.$confirm('确定要清除页面自定义配置吗？清除后将使用网站全局配置。', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        clearPageConfig(this.pageId).then(response => {
          this.$message.success('页面配置已清除')
          this.pageConfig = {}
          this.mergedConfig = response.data.merged_config
          this.jsonConfig = '{}'
          this.$emit('cleared')
        })
      }).catch(() => {
        // 取消操作
      })
    },
    // 处理 JSON 变化
    handleJsonChange() {
      try {
        this.pageConfig = JSON.parse(this.jsonConfig)
      } catch (e) {
        this.$message.error('JSON 格式错误')
      }
    },
    // 格式化 JSON
    formatJson() {
      try {
        const obj = JSON.parse(this.jsonConfig)
        this.jsonConfig = JSON.stringify(obj, null, 2)
        this.$message.success('已格式化')
      } catch (e) {
        this.$message.error('JSON 格式错误')
      }
    },
    // 验证 JSON
    validateJson() {
      try {
        JSON.parse(this.jsonConfig)
        this.$message.success('JSON 格式正确')
      } catch (e) {
        this.$message.error(`JSON 格式错误: ${e.message}`)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.page-config-editor {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-buttons {
      display: flex;
      gap: 10px;
    }
  }

  .config-preview {
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    overflow-x: auto;
    font-size: 13px;
    line-height: 1.6;
    max-height: 600px;
    overflow-y: auto;
  }
}
</style>
